package com.baidu.health.service;

import com.baidu.health.mapper.TbCaseContentMapper;
import com.baidu.health.pojo.CaseContentVo;
import com.baidu.health.pojo.TbCaseContent;
import com.baidu.health.util.PageResult;
import com.baidu.health.util.resFaqVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baidu.health.pojo.TbCase;
import com.baidu.health.service.TbCaseService;
import com.baidu.health.mapper.TbCaseMapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Service
public class TbCaseServiceImpl extends ServiceImpl<TbCaseMapper, TbCase>
    implements TbCaseService{

    @Autowired
    TbCaseMapper tbCaseMapper;
    @Autowired
    TbCaseContentMapper tbCaseContentMapper;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

//    @Override
//    public resFaqVo caseadd(TbCase tbCaseadd) {
//        tbCaseadd.setCaseStarttime(new Date());
//        tbCaseadd.setDeleted(1);
//        tbCaseMapper.insert(tbCaseadd);
//        return new resFaqVo(200, "成功", null);
//    }

    @Scheduled(cron = "0 0/5 * * * *")
    @Override
    public resFaqVo caseList() {
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        String a=simpleDateFormat.format(date);
        //String es=stringRedisTemplate.opsForValue().get("esredis");
        //if (es==null){
            List<TbCase> caselist=tbCaseMapper.selectList(null);
            //同步到es
            System.out.println("---"+"全量成功");
            elasticsearchRestTemplate.save(caselist);
            stringRedisTemplate.opsForValue().set("esredis", a);
            return new resFaqVo(200, "全量成功", caselist);
        //}else{
//            List<TbCase> casetimelist=tbCaseMapper.selectByTime(es);
//            //同步到es
//            System.out.println("---"+"增量成功");
//            elasticsearchRestTemplate.save(casetimelist);
//            stringRedisTemplate.opsForValue().set("esredis", a);
//            return new resFaqVo(200, "增量成功", casetimelist);
        //}
    }

    @Override
    public resFaqVo casePage(TbCase tbCase) {
        Page<TbCase> page=new Page<>(tbCase.getCurrent(),tbCase.getPagesize());
        QueryWrapper<TbCase> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("deleted", 1);
        queryWrapper.orderByDesc("case_starttime");
        Page<TbCase> page1=tbCaseMapper.selectPage(page,queryWrapper);
        return new resFaqVo(200, "成功", page1);
    }

    @Override
    public resFaqVo caseDelete(TbCase tbCasea) {
        //tbCasea.setDeleted(0);
        System.out.println(tbCasea.getCaseId());
        tbCaseMapper.updateByCaseId(tbCasea.getCaseId());
        return new resFaqVo(200, "成功", null);
    }

    @Override
    public resFaqVo caseEsPage(TbCase tbCasees) {
        if(tbCasees.getCaseName()==null){//疾病id为空
            NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();

            BoolQueryBuilder bool=new BoolQueryBuilder();
            if (tbCasees.getAskDiseaser()!=null) {
                bool.must(QueryBuilders.matchQuery("askDiseaser", tbCasees.getAskDiseaser()));
            }
            bool.must(QueryBuilders.matchQuery("deleted", 1));
            NativeSearchQuery nativeSearchQuery=builder
                    .withQuery(bool)
                    .withPageable(PageRequest.of(tbCasees.getCurrent()-1, tbCasees.getPagesize()))
                    .withSort(SortBuilders.fieldSort("caseStarttime").order(SortOrder.DESC))
                    .build();
            List list=new ArrayList();
            Long total=elasticsearchRestTemplate.search(nativeSearchQuery, TbCase.class).getTotalHits();
            SearchHits<TbCase> searchHits=elasticsearchRestTemplate.search(nativeSearchQuery, TbCase.class);
            List<SearchHit<TbCase>> list1=searchHits.getSearchHits();
            for (SearchHit<TbCase> tbCaseSearchHit : list1) {
                TbCase a=tbCaseSearchHit.getContent();
                list.add(a);
            }
//            PageResult<TbCase> pageResult=new PageResult<>(total, list);
            HashMap<String, Object> map = new HashMap<>();
            map.put("list",list);
            map.put("total",total);
            return new resFaqVo(200, "sjkhsjs成功", map);
        }
        else{
            NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();

            BoolQueryBuilder bool=new BoolQueryBuilder();
            if (tbCasees.getCaseName()!=null && tbCasees.getCaseName()!=""){
                bool.must(QueryBuilders.matchQuery("caseName", tbCasees.getCaseName()));
            }
            if (tbCasees.getAskDiseaser()!=null){
                bool.must(QueryBuilders.matchQuery("askDiseaser", tbCasees.getAskDiseaser()));
            }
            bool.must(QueryBuilders.matchQuery("deleted", 1));
            HighlightBuilder highlightBuilder=new HighlightBuilder();
            highlightBuilder.preTags("<b style='color: red'>");
            highlightBuilder.postTags("</b>");
            highlightBuilder.field("caseName");
            NativeSearchQuery nativeSearchQuery=builder
                    .withQuery(bool)
                    .withHighlightBuilder(highlightBuilder)
                    .withSort(SortBuilders.fieldSort("caseStarttime").order(SortOrder.DESC))
                    .withPageable(PageRequest.of(tbCasees.getCurrent()-1, tbCasees.getPagesize()))
                    .build();
            List list=new ArrayList();
            Long total=elasticsearchRestTemplate.search(nativeSearchQuery, TbCase.class).getTotalHits();
            SearchHits<TbCase> searchHits=elasticsearchRestTemplate.search(nativeSearchQuery, TbCase.class);
            List<SearchHit<TbCase>> list1=searchHits.getSearchHits();
            for (SearchHit<TbCase> tbCaseSearchHit : list1) {
                TbCase a=tbCaseSearchHit.getContent();
                List<String> b=tbCaseSearchHit.getHighlightField("caseName");
                a.setCaseName(b.get(0));
                list.add(a);
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("list",list);
            map.put("total",total);
            //PageResult<TbCase> pageResult=new PageResult<>(total, list);
            return new resFaqVo(200, "fhsfshf成功", map);
        }
    }

    @Override
    public resFaqVo caseadd(CaseContentVo caseContentVo) {
        tbCaseMapper.insert(caseContentVo);

        System.out.println(caseContentVo.getTbCaseContents());
        Integer ids=tbCaseMapper.selectByName(caseContentVo.getCaseName());
        List<TbCaseContent> list=caseContentVo.getTbCaseContents();
        for (TbCaseContent tbCaseContent : list) {
            tbCaseContent.setCaseid(ids);
            tbCaseContent.setStarttime(new Date());
            tbCaseContentMapper.insert(tbCaseContent);
            this.caseList();
            rabbitTemplate.convertAndSend("wyqyk1230", "添加了新的方案");
        }

        return new resFaqVo(200, "成功",null);
    }

//    @Override
//    public void caseDelete(Integer cid) {
//        //tbCaseMapper.deleteById(cid);
//        tbCaseMapper.updateBystate(cid);
//        //删除方案的时候把输入方案的方案内容也删除
//        Integer caseid=cid;
//        //tbCaseContentMapper.deleteByCaseId(caseid);
//        tbCaseContentMapper.updateBystate(cid);
//    }

    @Override
    public List<TbCase> caseByaskDiseaser(Integer askDiseaser) {
        List<TbCase> caseByackDiseaserlist=tbCaseMapper.caseByackDiseaser(askDiseaser);
        return caseByackDiseaserlist;
    }
}




